package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.WeiboMapper;
import cn.tedu.weibo.pojo.dto.WeiboDto;
import cn.tedu.weibo.pojo.entity.Weibo;
import cn.tedu.weibo.pojo.vo.UserVO;
import cn.tedu.weibo.pojo.vo.WeiboDetailVO;
import cn.tedu.weibo.pojo.vo.WeiboIndexVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;
    @RequestMapping("/weibo/insert")
    public int insert(@RequestBody WeiboDto weibo, HttpSession session){
        //从会话对象中得到登录成功时保存的用户对象
        UserVO user = (UserVO) session.getAttribute("user");
        //判断是否有user对象
        if (user==null){//说明未登录
            return 2;
        }
        System.out.println("weibo = " + weibo);
        Weibo w = new Weibo();
        //把dto里面的数据装进实体类
        BeanUtils.copyProperties(weibo,w);
        //给实体类中的属性赋值
        w.setCreated(new Date());
        //设置作者的id(当前登录用户的id)
        w.setUserId(user.getId());
        //调用mapper的insert方法
        mapper.insert(w);
        return 1;
    }
    @RequestMapping("/weibo/select")
    public List<WeiboIndexVO> select(){
        return mapper.select();
    }
    @RequestMapping("/weibo/selectById")
    public WeiboDetailVO selectById(int id){
        //当return的内容为自定义对象或List集合时,SpringMVC框架会自动将其转成
        //JSON格式的字符串 再通过网络传输出去.
        return mapper.selectById(id);
    }
}
